package com.wwwarehouse.usercenter.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wwwarehouse.common.activity.ChangeEnvActivity;
import com.wwwarehouse.common.activity.base.BaseActivity;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.common.Common;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.button.StateButton;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.DeviceUtils;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tools.rsa.Base64Utils;
import com.wwwarehouse.common.tools.rsa.RSAUtil;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.bean.response.BindDeviceResponseBean;
import com.wwwarehouse.usercenter.bean.response.LoginResponseBean;
import com.wwwarehouse.usercenter.bean.response.TimingDialogResponseBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;
import com.wwwarehouse.usercenter.eventbus_event.ConfirmDialogEvent;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;

/**
 * Created by Jackie on 2017/6/23.
 * 登录界面
 */

@Route(path = UserCenterConstant.PATH_LOGIN_ACTIVITY)
public class LoginActivity extends BaseActivity implements View.OnClickListener, TextWatcher, ClearEditText.onMyFocusChangeListener {
    private View mRootView;

    private TextView mErrorTxt;

    private ClearEditText mUsernameEdt;
    private View mUsernameLine;
    private ClearEditText mPasswordEdt;
    private ImageView mEyeImg;
    private View mPasswordLine;
    private LinearLayout mCodeLayout;
    private ClearEditText mCodeEdt;
    private View mCodeLine;
    private ImageView mCodeImg;

    private StateButton mLoginBtn;
    private TextView mForgetTxt;
    private ImageView mWechatImg;
    private TextView mRegisterTxt;

    private Button mSwitchBtn;     // 切换环境按钮
    private Button mShowSwitchBtn; // 显示切换环境的按钮

    private boolean mIsEyeOpened = false;

    private IWXAPI mApi;

    //是否显示确认对话框
    private boolean mIsShowingConfirmDialog = false;

    private RequestQueue mRequestQueue;

    public static final String KEY_INPUT_USERNAME = "key_input_username";

    private static final int REQUEST_LOGIN_ACCOUNT = 0;
    private static final int REQUEST_LOGIN_OUT = 1;
    private static final int REQUEST_GET_VERIFICATION_IMAGE = 2;
    private static final int REQUEST_AUTHENTICATION_CODE = 3;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        Common.getInstance().removeActivity(this);

        initView();
        initEvent();
    }

    private void initView() {
        mRootView = findView(R.id.rl_root);
        mShowSwitchBtn = findView(R.id.show_switch_evn_bt);

        mErrorTxt = findView(R.id.tv_error);

        mUsernameEdt = findView(R.id.et_username);
        mUsernameLine = findView(R.id.v_username);
        mPasswordEdt = findView(R.id.et_password);
        mEyeImg = findView(R.id.iv_eye);
        mPasswordLine = findView(R.id.v_password);
        mCodeLayout = findView(R.id.ll_code);
        mCodeEdt = findView(R.id.et_code);
        mCodeLine = findView(R.id.v_code);
        mCodeImg = findView(R.id.iv_code);

        mLoginBtn = findView(R.id.btn_login);

        mForgetTxt = findView(R.id.tv_forget);
        mWechatImg = findView(R.id.iv_wechat);
        mRegisterTxt = findView(R.id.tv_register);
        mRegisterTxt.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.DITHER_FLAG | Paint.ANTI_ALIAS_FLAG); //下划线

        mSwitchBtn = findView(R.id.btn_switch_env);

        mRequestQueue = NoHttp.newRequestQueue();

        initChangeEnvBtn();

        if(LogUtils.isDebug()){
            mSwitchBtn.setVisibility(View.VISIBLE);
        }else{
            mSwitchBtn.setVisibility(View.GONE);
        }

        EventBus.getDefault().register(this);
    }

    private void initEvent() {
        mRootView.setOnClickListener(this);

        mUsernameEdt.addTextChangedListener(this);
        mUsernameEdt.setOnMyFocusChangeListener(this);
        mPasswordEdt.addTextChangedListener(this);
        mPasswordEdt.setOnMyFocusChangeListener(this);
        mPasswordEdt.setLongClickable(false);
        mPasswordEdt.setTextIsSelectable(false);
        mEyeImg.setOnClickListener(this);
        mCodeEdt.addTextChangedListener(this);
        mCodeEdt.setOnMyFocusChangeListener(this);
        mCodeImg.setOnClickListener(this);

        mLoginBtn.setOnClickListener(this);
        mShowSwitchBtn.setOnClickListener(this);
        mForgetTxt.setOnClickListener(this);
        mWechatImg.setOnClickListener(this);
        mRegisterTxt.setOnClickListener(this);
        mSwitchBtn.setOnClickListener(this);
    }

    private void initChangeEnvBtn() {
        String env = sp.getValue(Constant.sp_EnvDefault, Constant.ENV_DEFAULT);

        if (Constant.ENV_DEV.equals(env)) {
            mSwitchBtn.setText("当前环境是DEV");
        } else if (Constant.ENV_CIT.equals(env)) {
            mSwitchBtn.setText("当前环境是CIT");
        } else if (Constant.ENV_SIT.equals(env)) {
            mSwitchBtn.setText("当前环境是SIT");
        } else if (Constant.ENV_UAT.equals(env)) {
            mSwitchBtn.setText("当前环境是UAT");
        } else if (Constant.ENV_RELEASE.equals(env)) {
            mSwitchBtn.setText("当前环境是RELEASE");
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.rl_root) {
            hideSoftKeyBoard(mRootView);
        } else if (id == R.id.iv_eye) {
            if (!mIsEyeOpened) {
                mEyeImg.setImageResource(R.drawable.login_open_eye);
                mPasswordEdt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                mEyeImg.setImageResource(R.drawable.login_close_eye);
                mPasswordEdt.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }

            mPasswordEdt.postInvalidate();

            mIsEyeOpened = !mIsEyeOpened;

            CharSequence charSequence = mPasswordEdt.getText();
            if (charSequence instanceof Spannable) {
                Spannable spannable = (Spannable) charSequence;
                Selection.setSelection(spannable, charSequence.length());
            }
        } else if (id == R.id.iv_code) {    //换一换
            generateImageCode();
        } else if (id == R.id.btn_login) {
            login();
        } else if (id == R.id.tv_forget) {
            Bundle bundle = new Bundle();
            bundle.putString(KEY_INPUT_USERNAME, mUsernameEdt.getText().toString().trim());

            startActivity(ForgetPasswordStep1Activity.class, bundle, false);
        } else if (id == R.id.iv_wechat) {
            if (mApi == null) {
                mApi = WXAPIFactory.createWXAPI(this, BaseApplication.getApplicationInstance().getAPP_ID(), false);
            }

            if (!mApi.isWXAppInstalled()) {
                toast(R.string.wechat_not_installed);
                return;
            }

            mApi.registerApp(BaseApplication.getApplicationInstance().getAPP_ID());
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "weixin";

            mApi.sendReq(req);

            mIsShowingConfirmDialog = false;
        } else if (id == R.id.tv_register) {
            if (mApi == null) {
                mApi = WXAPIFactory.createWXAPI(this, BaseApplication.getApplicationInstance().getAPP_ID(), false);
            }

            if (!mApi.isWXAppInstalled()) {
                toast(R.string.wechat_not_installed);
                return;
            }

            mApi.registerApp(BaseApplication.getApplicationInstance().getAPP_ID());
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "weixin";

            mApi.sendReq(req);

            mIsShowingConfirmDialog = true;
        } else if (id == R.id.btn_switch_env) {
            startActivityForResult(ChangeEnvActivity.class, 1, null);
        } else if (id == R.id.show_switch_evn_bt) {
            showSwitchBt(); // 显示切换环境的按钮
        }
    }


    long mLastClickTime = 0; // 上次点击事件
    int mClickCount = 0; // 点击次数
    // 判断是不是快速点击，返回true表示不是
    public boolean isInTwoSecond() {
        long time = System.currentTimeMillis();
        if (time - mLastClickTime <= 1000) {
            mLastClickTime = time;
            mClickCount++;
            return true;
        } else {
            mLastClickTime = time;
            mClickCount = 0;
            return false;
        }
    }


    private void showSwitchBt() {
        if (isInTwoSecond() && mClickCount >= 6) {
            mSwitchBtn.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 1 && requestCode == 1) {
            initChangeEnvBtn();
        }

        if (resultCode == 3 && requestCode == REQUEST_AUTHENTICATION_CODE) {
            startActivity(UserCenterConstant.PATH_MAIN, null, true);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        checkLoginEnable();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        mUsernameLine.setBackgroundResource(R.color.usercenter_6e6e6e);
        mPasswordLine.setBackgroundResource(R.color.usercenter_6e6e6e);
        mCodeLine.setBackgroundResource(R.color.usercenter_6e6e6e);

        if (view instanceof ClearEditText && hasFocus) {
            int id = view.getId();

            if (id == R.id.et_username) {
                mErrorTxt.setTextColor(getResources().getColor(R.color.usercenter_6e6e6e));
                mErrorTxt.setText(R.string.pls_input_username);

                mUsernameLine.setBackgroundResource(R.color.usercenter_000000);
            } else if (id == R.id.et_password) {
                mErrorTxt.setTextColor(getResources().getColor(R.color.usercenter_6e6e6e));
                mErrorTxt.setText(R.string.pls_input_password);

                mPasswordLine.setBackgroundResource(R.color.usercenter_000000);
            } else if (id == R.id.et_code) {
                mErrorTxt.setTextColor(getResources().getColor(R.color.usercenter_6e6e6e));
                mErrorTxt.setText(R.string.pls_input_code);

                mCodeLine.setBackgroundResource(R.color.usercenter_000000);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mRequestQueue.cancelAll();

        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(ConfirmDialogEvent event) {
        //弹出微信确认登录对话框
        if (mIsShowingConfirmDialog) {
            DialogTools.getInstance().showCustomDialogPromptNoTitleCancleListen(mContext, getString(R.string.you_has_account_login_or_not), false,
                    new DialogTools.ConfirmListener() {
                        @Override
                        public void setConfirmListener(Dialog dialog, View view, String s) {
                            dialog.dismiss();

                            //跳转到登录界面
                            startActivity(UserCenterConstant.PATH_MAIN, null, true);
                        }
                    }, new DialogTools.DismissListener() {
                        @Override
                        public void setDismissListener(Dialog dialog, View view) {
                            dialog.dismiss();

                            //清掉登录信息
                            sp.deleteValue(mContext, Constant.sp_Person_Name);
                            sp.deleteValue(mContext, Constant.sp_Face_Url);
                            sp.deleteValue(mContext, Constant.sp_User_Account);
                            sp.deleteValue(mContext, Constant.sp_User_Id);

                            sp.deleteValue(mContext, Constant.sp_Token);
                        }
                    }, getString(R.string.login_directly), getString(R.string.login_exit));
        } else {
            //跳转到登录界面
            startActivity(UserCenterConstant.PATH_MAIN, null, true);
        }
    }

    /**
     * 微信登录，新用户未注册，跳转到注册页面，注册成功后，跳转到卡片桌面，结束当前登录页面
     * @param msg
     */
    public void onEventMainThread(String msg) {
        if ("REGISTER_SUCCESS".equals(msg)) {
            finishActivity();
        }
    }

    /**
     * 登录
     */
    private void login() {
        showProgressDialog(getString(R.string.logining));

        Map map = new HashMap();

        map.put("deviceInfo", DeviceUtils.getDeviceInfo(this));
        map.put("deviceMac", DeviceUtils.getDeviceMac());
        map.put("deviceToken", JPushInterface.getRegistrationID(BaseApplication.getApplicationInstance()));
        map.put("deviceType", "a_v");
        map.put("userAccount", mUsernameEdt.getText().toString().trim());

        String password = mPasswordEdt.getText().toString().trim();

        try {
            byte[] data = RSAUtil.encryptByPublicKey(password.getBytes(), RSAUtil.publicKey);
            password = Base64Utils.encodeBase64(data);

            map.put("password", password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        map.put("verificationCode", mCodeEdt.getText().toString().trim());

        NoHttpUtils.httpPost(UserCenterConstant.URL_LOGIN_ACCOUNT, map, mOnResponseListener, REQUEST_LOGIN_ACCOUNT);
    }

    private void loginOut() {
        showProgressDialog(getString(R.string.login_outing));

        Map map = new HashMap();

        map.put("deviceType", "a_v");

        NoHttpUtils.httpPost(UserCenterConstant.URL_LOGIN_OUT, map, mOnResponseListener, REQUEST_LOGIN_OUT);
    }

    /**
     * 生成图片验证码
     */
    private void generateImageCode() {
        Map map = new HashMap();
        map.put("deviceInfo", DeviceUtils.getDeviceInfo(this));

        final Request<byte[]> request = NoHttpUtils.getByteRequest(UserCenterConstant.URL_GET_IMAGE_VERIFICATION, map, RequestMethod.GET);

        mRequestQueue.add(REQUEST_GET_VERIFICATION_IMAGE, request, new OnResponseListener<byte[]>() {
            @Override
            public void onStart(int what) {

            }

            @Override
            public void onSucceed(int what, Response<byte[]> response) {
                mCodeLayout.setVisibility(View.VISIBLE);

                byte[] bytes = response.get();
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                mCodeImg.setImageBitmap(bitmap);

                checkLoginEnable();
            }

            @Override
            public void onFailed(int what, Response<byte[]> response) {
                LogUtils.showLog(response.getException().toString());
            }

            @Override
            public void onFinish(int what) {

            }
        });
    }

    private void checkLoginEnable() {
        if (mCodeLayout.getVisibility() == View.VISIBLE) {
            if (!TextUtils.isEmpty(mUsernameEdt.getText().toString().trim()) &&
                    !TextUtils.isEmpty(mPasswordEdt.getText().toString().trim()) &&
                    !TextUtils.isEmpty(mCodeEdt.getText().toString().trim())) {
                mLoginBtn.setEnabled(true);
                mLoginBtn.setNormalBackgroundColor(getResources().getColor(R.color.color_333333));
            } else {
                mLoginBtn.setEnabled(false);
                mLoginBtn.setNormalBackgroundColor(getResources().getColor(R.color.common_color_c8_d5d7dc));
            }
        } else {
            if (!TextUtils.isEmpty(mUsernameEdt.getText().toString().trim()) &&
                    !TextUtils.isEmpty(mPasswordEdt.getText().toString().trim())) {
                mLoginBtn.setEnabled(true);
                mLoginBtn.setNormalBackgroundColor(getResources().getColor(R.color.color_333333));
            } else {
                mLoginBtn.setEnabled(false);
                mLoginBtn.setNormalBackgroundColor(getResources().getColor(R.color.common_color_c8_d5d7dc));
            }
        }
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_LOGIN_ACCOUNT:
                    if ("0".equals(commonClass.getCode())) {  //请求成功
                        //将token存到SharedPreference中
                        LoginResponseBean loginResponseBean = JSON.parseObject(commonClass.getData().toString(), LoginResponseBean.class);
                        LoginResponseBean.UserInfoBean userInfoBean = loginResponseBean.getUserInfo();

                        if (userInfoBean != null) {
                            sp.putValue(Constant.sp_Person_Name, userInfoBean.getPersonName());
                            sp.putValue(Constant.sp_Face_Url, userInfoBean.getFaceUrl());
                            sp.putValue(Constant.sp_User_Account, userInfoBean.getUserAccount());
                            sp.putValue(Constant.sp_User_Id, userInfoBean.getUserId());
                        }

                        sp.putValue(Constant.sp_Token, loginResponseBean.getToken());

                        startActivity(UserCenterConstant.PATH_MAIN, null, true);
                    } else if ("200005".equals(commonClass.getCode())) {  //200005 密码输入错误3次，锁定输入
                        if (commonClass.getData() != null) {
                            TimingDialogResponseBean timingDialogResponseBean = JSON.parseObject(commonClass.getData().toString(), TimingDialogResponseBean.class);
                            DialogTools.getInstance().showCustomTiming(LoginActivity.this, getString(R.string.dialog_1_title), commonClass.getMsg(), timingDialogResponseBean.getTime(), false);
                        }
                    } else if ("200026".equals(commonClass.getCode())) {  //200026 密码输入错误5次，锁定输入同时出现图片验证码
                        mErrorTxt.setTextColor(getResources().getColor(R.color.usercenter_ff0000));
                        mErrorTxt.setText(commonClass.getMsg());

                        //图片验证码
                        generateImageCode();

                        if (commonClass.getData() != null) {
                            TimingDialogResponseBean timingDialogResponseBean = JSON.parseObject(commonClass.getData().toString(), TimingDialogResponseBean.class);
                            DialogTools.getInstance().showCustomTiming(LoginActivity.this, getString(R.string.dialog_1_title), commonClass.getMsg(), timingDialogResponseBean.getTime(), false);
                        }
                    } else if ("200034".equals(commonClass.getCode())) {  //200034  绑定设备
                        BindDeviceResponseBean bindDeviceResponseBean = JSON.parseObject(commonClass.getData().toString(), BindDeviceResponseBean.class);

                        Bundle bundle = new Bundle();
                        bundle.putString(UserCenterConstant.KEY_LOGIN_MOBILE, bindDeviceResponseBean.getMobile());     //绑定设备的手机号
                        bundle.putString(UserCenterConstant.KEY_LOGIN_ERROR, bindDeviceResponseBean.getLoginError());  //登录异常值

                        //绑定设备，先做身份验证
                        startActivityForResult(AuthenticationActivity.class, REQUEST_AUTHENTICATION_CODE, bundle);
                    } else {
                        mErrorTxt.setTextColor(getResources().getColor(R.color.usercenter_ff0000));
                        mErrorTxt.setText(commonClass.getMsg());
                    }
                    break;
                case REQUEST_LOGIN_OUT:
                    if ("0".equals(commonClass.getCode())) {
                        //登出成功
                    } else {
                        toast(commonClass.getMsg());
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            toast(result);
        }

        @Override
        public void onFinish(int what) {
            dismissProgress();
        }
    };
}
